from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from app01.models import Person
from django.core import serializers
import json
import time


# Create your views here.
def index(request):
    print('666666666666666666', request.META["REMOTE_ADDR"])
    print('666666666666666666', request.path)
    print('666666666666666666', request.COOKIES)
    time.sleep(1)
    return HttpResponse('欢迎使用')


# 返回html文件
def html_test(request):
    return render(request, 'example.html')


# 模板语法练习
def template_language(request):
    person01 = {'name': "张三", 'age': 18}
    print('666666666666666666', request.META["REMOTE_ADDR"])
    print('666666666666666666', request.path)
    print('666666666666666666', request.COOKIES)
    return render(request, 'template_language.html',
                  {'department': "市场部", 'person': person01, 'floor': ['1楼', '3楼', '5楼']})


def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        if username == '123' and password == '123':
            return redirect('http://www.baidu.com')
        else:
            return render(request, 'login.html', {'msg': '登录失败,请重新登录'})


# http://127.0.0.1:8000/get_data
def get_base_data(request):
    # data = Person.objects.filter(id=1).last()
    # Person.objects.create(name='张良2', age=26, sex='男', country='魏', job=2)
    # Person.objects.filter(name='张良').delete()
    # for i in data:
    #     print(i.name)
    Person.objects.filter(name='周瑜').update(name='张良')
    data = Person.objects.filter(name='张良').all()
    data = serializers.serialize('json', data, fields=['name', 'age', 'sex', 'job'])
    time.sleep(3)
    return HttpResponse(data)
    # return redirect('/index')


# http://127.0.0.1:8000/locust_test
def locust_test(request):
    """
    测试locust使用
    :param request:
    :return:
    """
    t1 = time.time()
    list_my = [i for i in range(0, 10000000)]
    t2 = time.time()
    data = json.dumps({'msg': '测试结束', 'code': 1, 'run_time': f'{t2 - t1}'})
    print(len(data.encode('gbk')))
    return HttpResponse(data)
